import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:speed_random/app_styles.dart';
import 'package:speed_random/common/common_fuc.dart';
import 'package:speed_random/pages/home/rand_com/logic.dart';
import 'package:speed_random/pages/home/rand_com/state.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 将 StatelessWidget 改为 StatefulWidget
class ViewBodyPassword extends StatefulWidget {
  final RandComLogic logic;
  final RandComState state;

  const ViewBodyPassword({Key? key, required this.logic, required this.state}) : super(key: key);

  @override
  _ViewBodyPasswordState createState() => _ViewBodyPasswordState();
}

class _ViewBodyPasswordState extends State<ViewBodyPassword> {
  late TextEditingController _passwordController;
  bool _useUppercase = true;
  bool _useNumbers = true;
  bool _useLowercase = true;
  bool _useSpecialChars = true;
  int useLength = 4;

  /// 加载缓存中的设置
  Future<void> _loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _useUppercase = prefs.getBool('useUppercase') ?? true;
      _useNumbers = prefs.getBool('useNumbers') ?? true;
      _useLowercase = prefs.getBool('useLowercase') ?? true;
      _useSpecialChars = prefs.getBool('useSpecialChars') ?? true;
      useLength = prefs.getInt('useLength') ?? 4;
    });
  }

  /// 保存设置到缓存
  Future<void> _saveSettings() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('useUppercase', _useUppercase);
    await prefs.setBool('useNumbers', _useNumbers);
    await prefs.setBool('useLowercase', _useLowercase);
    await prefs.setBool('useSpecialChars', _useSpecialChars);
    await prefs.setInt('useLength', useLength);
  }

  @override
  void initState() {
    super.initState();
    _passwordController = TextEditingController();
    _passwordController.text = useLength.toString();
    _loadSettings();
  }

  @override
  void dispose() {
    _passwordController.dispose();
    super.dispose();
  }
// ... 已有代码 ...


  Future<void> generateRandomNumbersStart() async {
    int scrollTime = widget.state.scrollTime.value.clamp(1, 9);
    int loopCount = scrollTime * 10;
    if (widget.state.isManualStop.value) {
      loopCount = 10000;
    }
    widget.logic.payRunMp3();
    for (int i = 0; i < loopCount; i++) {
        if(widget.state.isRun.value != 1){
          break;
        }
      // print(i);
      await Future.delayed(const Duration(milliseconds: 100));
      startSpin();
      // 声音提示
    }
    widget.logic.payRunMp3(type: "stop");
  }


  stopSpin() {
    widget.state.isRun.value = 0;
  }

  startSpin() {
    // 获取输入的密码长度
    final passwordLengthStr = _passwordController.text;
    int passwordLength = int.tryParse(passwordLengthStr) ?? 8;
    if (passwordLength < 1) {
      passwordLength = 8;
    }

    // 定义不同类型的字符集
    const uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
    const numbers = '0123456789';
    const specialChars = '!@#\$%^&*()_+-=[]{}|;:,.<>?';

    // 根据勾选状态构建可用字符集
    String allChars = '';
    List<String> requiredChars = [];

    if (_useUppercase) {
      allChars += uppercaseLetters;
      requiredChars.add(uppercaseLetters[Random().nextInt(uppercaseLetters.length)]);
    }
    if (_useLowercase) {
      allChars += lowercaseLetters;
      requiredChars.add(lowercaseLetters[Random().nextInt(lowercaseLetters.length)]);
    }
    if (_useNumbers) {
      allChars += numbers;
      requiredChars.add(numbers[Random().nextInt(numbers.length)]);
    }
    if (_useSpecialChars) {
      allChars += specialChars;
      requiredChars.add(specialChars[Random().nextInt(specialChars.length)]);
    }

    // 如果没有勾选任何字符类型，默认使用小写字母
    if (allChars.isEmpty) {
      allChars = lowercaseLetters;
      requiredChars.add(lowercaseLetters[Random().nextInt(lowercaseLetters.length)]);
    }

    // 生成剩余的随机字符
    List<String> passwordChars = [];
    for (int i = 0; i < passwordLength - requiredChars.length; i++) {
      passwordChars.add(allChars[Random().nextInt(allChars.length)]);
    }

    // 合并必须包含的字符和随机生成的字符
    passwordChars.addAll(requiredChars);

    // 打乱字符顺序
    passwordChars.shuffle();

    // 更新状态
    widget.state.randomNumbers.value = passwordChars;
  }






  @override
  Widget build(BuildContext context) {

    widget.state.funStart = generateRandomNumbersStart;
    widget.state.funStop = stopSpin;

    // 这里是公共部分组建。
    return
        Card(
      color: widget.state.randComArgs.value.colorPagebg,
      // 使用 Obx 响应式组件
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [


          Expanded(child:
      Column(
      crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(()=>
                Text(
                  widget.state.randomNumbers.value.join(""),
                  style: TextStyle(
                      fontSize: commonFuc.calculateFontSize(widget.state.randomNumbers.value.join(""), context),
                      color: widget.state.randComArgs.value.colorPageText,
                      fontWeight: FontWeight.bold
                  ),
                ),)

            ,
            SizedBox(height: 20,),
            // 复制按钮
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: AppStyles.colorOkButbg,
              ),
              onPressed: () {
                // 复制到剪贴板
                Clipboard.setData(ClipboardData(text: widget.state.randomNumbers.value.join("")));
                // 显示提示
                ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('已复制到剪贴板'.tr)));
              },
              child: Text('复制'.tr,style: TextStyle(color: Colors.white),),
            ),
          ]),),


Padding(padding: EdgeInsetsGeometry.all(20),
child:
    TextField(
    controller: _passwordController,
    obscureText: false,
    style: TextStyle(color: Colors.black),
    decoration:  InputDecoration(
    labelText: '密码长度'.tr,
    labelStyle: TextStyle(color: Colors.black),
    // 输入法文本颜色
    border: OutlineInputBorder(),
    ),
    ),),
              CheckboxListTile(
                title:  Text('大写字母'.tr,style: TextStyle(color: Colors.black),),
                value: _useUppercase,
                onChanged: (bool? value) {
                  if (value != null) {
                    setState(() {
                      _useUppercase = value;
                    });
                    _saveSettings();
                  }
                },
              ),
              CheckboxListTile(
                title:  Text('小写字母'.tr,style: TextStyle(color: Colors.black),),
                value: _useLowercase,
                onChanged: (bool? value) {
                  if (value != null) {
                    setState(() {
                      _useLowercase = value;
                    });
                    _saveSettings();
                  }
                },
              ),

              CheckboxListTile(
                title:  Text('数字'.tr,style: TextStyle(color: Colors.black),),
                value: _useNumbers,
                onChanged: (bool? value) {
                  if (value != null) {
                    setState(() {
                      _useNumbers = value;
                    });
                    _saveSettings();
                  }
                },
              ),
              CheckboxListTile(
                title:  Text('特殊字符'.tr,style: TextStyle(color: Colors.black),),
                value: _useSpecialChars,
                onChanged: (bool? value) {
                  if (value != null) {
                    setState(() {
                      _useSpecialChars = value;
                    });
                    _saveSettings();
                  }
                },
              ),

        ],
      )
    );
  }
}
